package work.soho.proxy.aliyun.parts;

import com.aliyuncs.ecs.model.v20140526.*;

public class SecurityGroupPart extends BasePart implements IPart{
    /**
     * 安全组名称
     */
    private String securityGroupName = "ProxySshSocket5-dfhwvmkhfsdf";

    @Override
    public boolean isExist() {
        return getId() != null;
    }

    @Override
    public String getId() {
        DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
        describeSecurityGroupsRequest.setSecurityGroupName(securityGroupName);

        DescribeSecurityGroupsResponse describeAccessPointsResponse = callOpenApi(describeSecurityGroupsRequest);
        if(describeAccessPointsResponse.getTotalCount()>0) {
            return describeAccessPointsResponse.getSecurityGroups().get(0).getSecurityGroupId();
        }
        return null;
    }

    @Override
    public void drop() {
        //nothing todo
    }

    @Override
    public void create() {
        CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();
        createSecurityGroupRequest.setVpcId(configure.getVpcId());
        createSecurityGroupRequest.setDescription("香港代理服务器， 请保证ssh访问端口（22）可用, 其他程序请勿使用该安全组，会自动进行释放");
        createSecurityGroupRequest.setSecurityGroupName(securityGroupName);
        createSecurityGroupRequest.setSecurityGroupType("normal");
        CreateSecurityGroupResponse createSecurityGroupResponse = (CreateSecurityGroupResponse)callOpenApi(createSecurityGroupRequest);
        if(createSecurityGroupResponse != null &&createSecurityGroupResponse.getSecurityGroupId() != null) {
            //添加防火墙22端口入规则
            AuthorizeSecurityGroupRequest authorizeSecurityGroupRequest = new AuthorizeSecurityGroupRequest();
            authorizeSecurityGroupRequest.setRegionId(regionId);
            authorizeSecurityGroupRequest.setSecurityGroupId(createSecurityGroupResponse.getSecurityGroupId());
            authorizeSecurityGroupRequest.setIpProtocol("tcp");
            authorizeSecurityGroupRequest.setPortRange("22/22");
            authorizeSecurityGroupRequest.setSourceGroupId(createSecurityGroupResponse.getSecurityGroupId());
            authorizeSecurityGroupRequest.setSourceCidrIp("0.0.0.0/0");
            authorizeSecurityGroupRequest.setDescription("代理端口， 规则请勿动");
            AuthorizeSecurityGroupResponse authorizeSecurityGroupResponse = (AuthorizeSecurityGroupResponse) callOpenApi(authorizeSecurityGroupRequest);
        }
        configure.setSecurityGroupId(createSecurityGroupResponse.getSecurityGroupId());
    }

    @Override
    public void start() {
        //nothing todo
    }

    @Override
    public void configure() {
        configure.setSecurityGroupId(getId());
    }
}
